<template>
  <div class="page-container">
    <el-card class="page-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon size="20" class="header-icon"><Menu /></el-icon>
            <h3>菜单管理</h3>
            <span class="header-desc">管理系统菜单结构和权限</span>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="showAddMenu" :icon="Plus">
              新增菜单
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :model="searchForm" inline>
          <el-form-item label="菜单名称">
            <el-input 
              v-model="searchForm.menuName" 
              placeholder="请输入菜单名称" 
              clearable
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px;">
              <el-option label="启用" value="0" />
              <el-option label="禁用" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadMenus" :icon="Search">搜索</el-button>
            <el-button @click="resetSearch" :icon="Refresh">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table
        :data="menus"
        style="width:100%;"
        row-key="menuId"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        class="menu-table"
        v-loading="loading"
        element-loading-text="正在加载..."
        element-loading-background="rgba(255, 255, 255, 0.6)"
      >
        <el-table-column prop="menuName" label="菜单名称" min-width="200">
          <template #default="scope">
            <div class="menu-name-cell">
              <el-icon><component :is="getMenuIcon(scope.row.menuType)" /></el-icon>
              <span>{{ scope.row.menuName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由地址" min-width="150" />
        <el-table-column prop="component" label="组件路径" min-width="150" show-overflow-tooltip />
        <el-table-column prop="menuType" label="菜单类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.menuType === 'M' ? 'primary' : scope.row.menuType === 'C' ? 'success' : 'warning'">
              {{ getMenuTypeText(scope.row.menuType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-switch 
              v-model="scope.row.status" 
              active-value="0" 
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="orderNum" label="排序" width="80" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="editMenu(scope.row)" :icon="Edit">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteMenu(scope.row)" :icon="Delete">
              删除
            </el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无菜单数据" />
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadMenus"
          @current-change="loadMenus"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      v-model="showAdd" 
      :title="form.menuId ? '编辑菜单' : '新增菜单'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="form.menuType">
                <el-radio value="M">目录</el-radio>
                <el-radio value="C">菜单</el-radio>
                <el-radio value="F">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="路由地址" prop="path">
              <el-input v-model="form.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组件路径" prop="component">
              <el-input v-model="form.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权限标识" prop="perms">
              <el-input v-model="form.perms" placeholder="请输入权限标识" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" :min="0" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="菜单图标" prop="icon">
          <el-input v-model="form.icon" placeholder="请输入图标名称">
            <template #prepend>
              <el-icon><component :is="form.icon || 'Menu'" /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio value="0">启用</el-radio>
            <el-radio value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAdd=false">取消</el-button>
          <el-button type="primary" @click="saveMenu" :loading="saving">
            {{ saving ? '保存中...' : '保存' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Menu, Plus, Search, Refresh, Edit, Delete,
  Folder, Document, Setting
} from '@element-plus/icons-vue'

const menus = ref([])
const showAdd = ref(false)
const form = ref({})
const formRef = ref()
const saving = ref(false)
const loading = ref(false)

// 搜索表单
const searchForm = ref({
  menuName: '',
  status: ''
})

// 分页
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 表单验证规则
const formRules = {
  menuName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  menuType: [{ required: true, message: '请选择菜单类型', trigger: 'change' }],
  orderNum: [{ required: true, message: '请输入排序号', trigger: 'blur' }]
}

// 获取菜单图标
const getMenuIcon = (menuType) => {
  const iconMap = {
    'M': Folder,
    'C': Document,
    'F': Setting
  }
  return iconMap[menuType] || Menu
}

// 获取菜单类型文本
const getMenuTypeText = (menuType) => {
  const typeMap = {
    'M': '目录',
    'C': '菜单',
    'F': '按钮'
  }
  return typeMap[menuType] || '未知'
}

const loadMenus = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      ...searchForm.value
    }

    // 修复API路径
    const res = await request.get('/menu/list', { params })
    if (res.code === 200) {
      const payload = res.data ?? res
      const data = payload?.data ?? payload
      const records = data?.records ?? data?.list ?? data
      const total = data?.total ?? 0
      menus.value = Array.isArray(records) ? records : (records?.records ?? [])
      pagination.value.total = total
    }
  } catch (error) {
    console.error('加载菜单失败:', error)
    ElMessage.error('加载菜单失败')
  } finally {
    loading.value = false
  }
}

const resetSearch = () => {
  searchForm.value = { menuName: '', status: '' }
  pagination.value.pageNum = 1
  loadMenus()
}

const showAddMenu = () => {
  form.value = { 
    status: '0', 
    orderNum: 0,
    menuType: 'C',
    parentId: 0
  }
  showAdd.value = true
}

const saveMenu = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
  } catch {
    return
  }
  
  saving.value = true
  
  try {
    if (form.value.menuId) {
      // 修复API路径
      await request.put('/menu', form.value)
      ElMessage.success('修改成功')
    } else {
      // 修复API路径
      await request.post('/menu', form.value)
      ElMessage.success('添加成功')
    }
    showAdd.value = false
    loadMenus()
  } catch (error) {
    console.error('保存菜单失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

const editMenu = (row) => {
  form.value = { ...row }
  showAdd.value = true
}

const deleteMenu = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除菜单"${row.menuName}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 修复API路径
    await request.delete(`/menu/${row.menuId}`)
    ElMessage.success('删除成功')
    loadMenus()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除菜单失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleStatusChange = async (row) => {
  try {
    await request.put('/menu', { ...row })
    // ElMessage.success('状态更新成功') // 移除弹窗提示
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('状态更新失败')
    // 恢复原状态
    row.status = row.status === '0' ? '1' : '0'
  }
}

onMounted(() => {
  loadMenus()
})
</script>

<style scoped>
.page-container {
  padding: 0;
}

.page-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  color: #409eff;
}

.card-header h3 {
  margin: 0;
  color: #2c3e50;
  font-weight: 600;
}

.header-desc {
  color: #909399;
  font-size: 14px;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.menu-table {
  margin-bottom: 20px;
}

.menu-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-table__row) {
  transition: background-color 0.3s;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-button--small) {
  margin-left: 8px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>